#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
    int listen_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(listen_sock < 0)
    {
        perror("socket");
        return 0;

    }

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(28989);
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    int ret = bind(listen_sock, (struct sockaddr*)&addr, sizeof(addr));
    if(ret < 0)
    {
        perror("bind");
        return 0;

    }

    ret = listen(listen_sock, 5);
    if(ret < 0)
    {
        perror("listen");
        return 0;

    }


    while(1)
    {
        int new_sock = accept(listen_sock, NULL, NULL);
        if(new_sock < 0)
        {
            continue;

        }

        //创建子进程
        int pid = fork();
        if(pid < 0)
        {
            //创建子进程失败， 但是接受新连接成功
            close(new_sock);
            continue;
        }
        else if(pid == 0)
        {
            //child
            close(listen_sock);
            while(1)
            {
                //recv   and      send
                char buf[1024] = {0};

                ssize_t recv_size = recv(new_sock, buf, sizeof(buf) - 1, 0);
                if(recv_size < 0)
                {
                    perror("recv");
                    continue;
                }
                else if(recv_size == 0)
                {
                    printf("peer shutdown!!\n");
                    close(new_sock);

                    //子进程退出掉 -- TODO
                    exit(1);
                }

                printf("client say: \"%s\"\n", buf);

                memset(buf, '\0', sizeof(buf));
                strcpy(buf, "i am server");
                send(new_sock, buf, strlen(buf), 0);
            }
        }
        else
        {
            //father
            close(new_sock);
        }
    }
    return 0;
}
